package model

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	_ "gorm.io/gorm"
	"home-bank/common/format_time"
	"log"
)

const NotDeletedStatus = 1
const DeletedStatus = 2

var conn *gorm.DB

type (
	SomethingModel interface {
		Insert() error
		Update() error
		Delete() error
		FindOne() (*Something, error)
		GetList(page int, pageSize int) ([]Something, int64, error)
	}

	Something struct {
		Id          int64  `json:"id" gorm:"column:id"`
		Name        string `json:"name" gorm:"column:name"`
		CategoryId  int64  `json:"category_id" gorm:"column:category_id"`
		ContainerId int64  `json:"container_id" gorm:"column:container_id"`
		IsDelete    int64  `json:"is_delete" gorm:"column:is_delete"`
		CreateTime  string `json:"create_time" gorm:"column:create_time"` //todo 时间类型 待优化
		UpdateTime  string `json:"update_time" gorm:"column:update_time"`
	}
)

func init() {
	conn = ConnectDb()
}

func (*Something) TableName() string {
	return "something"
}

func ConnectDb() *gorm.DB {
	conn, err := gorm.Open(
		mysql.Open(
			"root:123456@tcp(127.0.0.1:3306)/home_bank?" +
				"charset=utf8mb4&parseTime=True&loc=Local&collation=utf8mb4_unicode_ci",
		),
	)
	if err != nil {
		log.Fatal("数据库连接失败：", err)
	}
	fmt.Println("连接数据库成功")
	return conn
}

func (m *Something) Insert() error {
	conn.Create(m)

	return nil
}

func (m *Something) Update() error {
	m.UpdateTime = format_time.GetCurrTime()
	db := conn.Model(m).Updates(m)

	if db.Error != nil {
		return db.Error
	}

	return nil
}

func (m *Something) Delete() error {
	conn.Model(m).Updates(m)
	return nil
}

func (m *Something) FindOne() (*Something, error) {
	return nil, nil
}

func (m *Something) GetList(page int, pageSize int) ([]Something, int64, error) {
	var result []Something
	var total int64
	conn.Model(m).Order("id desc").Where(m).Offset(page - 1).Limit(pageSize).Find(&result).Count(&total)

	return result, total, nil
}
